package it.infodea.tapestrydea.components.livegrid;

import java.util.List;

import org.apache.tapestry5.CSSClassConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationTracker;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.corelib.internal.InternalMessages;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PersistentLocale;

public class LGridErrors{
    /**
     * The banner message displayed above the errors. The default value is "You must correct the following errors before
     * you may continue.".
     */
    @Parameter("message:default-banner")
    private String banner;

    /**
     * The CSS class for the div element rendered by the component. The default value is "t-error".
     */
    @Parameter(name = "class", defaultPrefix="literal")
    private String className = CSSClassConstants.ERROR;

    // Allow null so we can generate a better error message if missing
    @Parameter
    private int colspan;

    @Parameter
    private ValidationTracker tracker;
    
    @Inject
    private PersistentLocale pl;
    
    void beginRender(MarkupWriter writer){
        if (tracker == null) throw new RuntimeException(InternalMessages.encloseErrorsInForm());
        if (!tracker.getHasErrors()) return;
        writer.element("tr", "class", className);
        Element td = writer.element("td");
        if(colspan > 0)td.attribute("colspan", String.valueOf(colspan));
        
        // Inner div for the banner text
        writer.element("div");
//        writer.write(banner);
        writer.write(banner);
        writer.end();

        List<String> errors = tracker.getErrors();

        if (!errors.isEmpty())
        {
            // Only write out the <UL> if it will contain <LI> elements. An empty <UL> is not
            // valid XHTML.

            writer.element("ul");

            for (String message : errors)
            {
                writer.element("li");
                writer.write(message);
                writer.end();
            }

            writer.end(); // ul
        }

        writer.end(); // td
        writer.end(); // tr

    }

}
